import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Button, Table, Space, Tag, Modal, message, Form, Input, Select, InputNumber, DatePicker, Upload, Row, Col } from 'antd';
import { PlusOutlined, UploadOutlined, DeleteOutlined, EditOutlined, SyncOutlined } from '@ant-design/icons';
import moment from 'moment';
import { queryMeituanGroups, addMeituanGroup, updateMeituanGroup, deleteMeituanGroup } from './service';
import { request } from 'umi';

const { Option } = Select;
const { TextArea } = Input;
const { RangePicker } = DatePicker;

const MeituanGroupPage = () => {
  // 状态定义
  const [groups, setGroups] = useState([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [stores, setStores] = useState([]);
  const [fileList, setFileList] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [form] = Form.useForm();

  // 初始加载
  useEffect(() => {
    fetchStores();
    fetchGroups();
  }, []);

  // 获取门店列表
  const fetchStores = async () => {
    try {
      const response = await request('/api/v1/store', {
        method: 'GET',
        params: { pageSize: 100, status: 1 }, // 只获取启用的门店
      });
      setStores(response.data?.list || []);
    } catch (error) {
      console.error('获取门店列表失败:', error);
    }
  };

  // 获取美团团购活动列表
  const fetchGroups = async (params = {}) => {
    setLoading(true);
    try {
      const { current, pageSize, ...filters } = params;
      const response = await queryMeituanGroups({
        page: current || pagination.current,
        page_size: pageSize || pagination.pageSize,
        ...filters,
      });
      
      setGroups(response.data.list || []);
      setPagination({
        ...pagination,
        current: params.current || pagination.current,
        pageSize: params.pageSize || pagination.pageSize,
        total: response.data.total || 0,
      });
    } catch (error) {
      console.error('获取美团团购活动列表失败:', error);
      message.error('获取美团团购活动列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 表格分页变化
  const handleTableChange = (pagination, filters, sorter) => {
    fetchGroups({
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...filters,
    });
  };

  // 显示添加/编辑弹窗
  const showModal = (record = null) => {
    setEditingRecord(record);
    setVisible(true);
    
    // 重置表单
    form.resetFields();
    setFileList([]);
    
    // 如果是编辑，填充表单
    if (record) {
      // 处理图片
      let images = [];
      try {
        images = record.images ? JSON.parse(record.images) : [];
      } catch (e) {
        images = [];
      }
      
      // 设置文件列表
      const uploadFiles = images.map((url, index) => ({
        uid: `-${index}`,
        name: `图片${index + 1}`,
        status: 'done',
        url: url,
      }));
      
      setFileList(uploadFiles);
      
      // 设置表单值
      form.setFieldsValue({
        storeId: record.store_id,
        title: record.title,
        description: record.description,
        originalPrice: record.original_price / 100, // 转换为元
        groupPrice: record.group_price / 100, // 转换为元
        minCount: record.min_count,
        maxCount: record.max_count,
        timeRange: [
          moment(record.start_time),
          moment(record.end_time),
        ],
        activityRules: record.activity_rules,
        serviceTerms: record.service_terms,
        status: record.status,
        meituanGroupId: record.meituan_group_id,
      });
    } else {
      // 默认值
      form.setFieldsValue({
        minCount: 1,
        maxCount: 10,
        status: 1,
      });
    }
  };

  // 关闭弹窗
  const handleCancel = () => {
    setVisible(false);
    setEditingRecord(null);
  };

  // 处理图片上传
  const handleUploadChange = ({ fileList }) => {
    setFileList(fileList);
  };

  // 自定义上传
  const customUpload = async ({ file, onSuccess, onError }) => {
    const formData = new FormData();
    formData.append('file', file);
    
    try {
      const response = await request('/api/v1/upload', {
        method: 'POST',
        data: formData,
      });
      
      onSuccess(response, file);
    } catch (error) {
      onError(error);
    }
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      // 处理图片
      const images = fileList
        .filter(file => file.status === 'done')
        .map(file => file.url || (file.response && file.response.data));
      
      // 转换价格为分
      const originalPrice = Math.round(values.originalPrice * 100);
      const groupPrice = Math.round(values.groupPrice * 100);
      
      const formData = {
        store_id: values.storeId,
        title: values.title,
        description: values.description,
        original_price: originalPrice,
        group_price: groupPrice,
        min_count: values.minCount,
        max_count: values.maxCount,
        start_time: values.timeRange[0].valueOf(),
        end_time: values.timeRange[1].valueOf(),
        activity_rules: values.activityRules,
        service_terms: values.serviceTerms,
        status: values.status,
        images: JSON.stringify(images),
        meituan_group_id: values.meituanGroupId,
      };
      
      if (editingRecord) {
        // 更新
        await updateMeituanGroup(editingRecord.id, formData);
        message.success('更新成功');
      } else {
        // 新增
        await addMeituanGroup(formData);
        message.success('添加成功');
      }
      
      setVisible(false);
      fetchGroups();
    } catch (error) {
      console.error('保存美团团购活动失败:', error);
      message.error('保存失败，请检查表单');
    }
  };

  // 删除活动
  const handleDelete = async (id) => {
    try {
      await deleteMeituanGroup(id);
      message.success('删除成功');
      fetchGroups();
    } catch (error) {
      console.error('删除美团团购活动失败:', error);
      message.error('删除失败');
    }
  };

  // 确认删除
  const confirmDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除"${record.title}"活动吗？`,
      onOk: () => handleDelete(record.id),
    });
  };

  // 格式化时间戳
  const formatTimestamp = (timestamp) => {
    return timestamp ? moment(timestamp).format('YYYY-MM-DD') : '-';
  };

  // 表格列定义
  const columns = [
    {
      title: '门店名称',
      dataIndex: 'store_name',
      key: 'store_name',
    },
    {
      title: '美团团购ID',
      dataIndex: 'meituan_group_id',
      key: 'meituan_group_id',
    },
    {
      title: '活动标题',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
    },
    {
      title: '价格',
      key: 'price',
      render: (_, record) => (
        <span>
          ¥{(record.group_price / 100).toFixed(2)} / <del>¥{(record.original_price / 100).toFixed(2)}</del>
        </span>
      ),
    },
    {
      title: '开团人数',
      key: 'count',
      render: (_, record) => (
        <span>{record.min_count}-{record.max_count}人</span>
      ),
    },
    {
      title: '活动时间',
      key: 'time',
      render: (_, record) => (
        <span>
          {formatTimestamp(record.start_time)} 至 {formatTimestamp(record.end_time)}
        </span>
      ),
    },
    {
      title: '已售数量',
      dataIndex: 'sold_count',
      key: 'sold_count',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => showModal(record)}>编辑</a>
          <a onClick={() => confirmDelete(record)}>删除</a>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" onClick={() => showModal()} icon={<PlusOutlined />}>
            添加团购活动
          </Button>
        </div>
        <Table
          columns={columns}
          dataSource={groups}
          rowKey="id"
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
        />
      </Card>

      {/* 添加/编辑表单 */}
      <Modal
        title={editingRecord ? '编辑美团团购活动' : '添加美团团购活动'}
        visible={visible}
        onOk={handleSubmit}
        onCancel={handleCancel}
        width={800}
        okText="提交"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="storeId"
                label="所属门店"
                rules={[{ required: true, message: '请选择门店' }]}
              >
                <Select
                  placeholder="请选择门店"
                  disabled={editingRecord}
                >
                  {stores.map(store => (
                    <Option key={store.id} value={store.id}>{store.name || store.store_name}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                initialValue={1}
              >
                <Select>
                  <Option value={1}>启用</Option>
                  <Option value={0}>禁用</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="title"
            label="活动标题"
            rules={[{ required: true, message: '请输入活动标题' }]}
          >
            <Input placeholder="请输入活动标题" maxLength={100} />
          </Form.Item>

          <Form.Item
            name="meituanGroupId"
            label="美团团购ID"
            rules={[{ required: true, message: '请输入美团团购ID' }]}
          >
            <Input placeholder="请输入美团团购ID" maxLength={100} />
          </Form.Item>

          <Form.Item
            name="description"
            label="活动描述"
            rules={[{ required: true, message: '请输入活动描述' }]}
          >
            <TextArea placeholder="请输入活动描述" rows={4} maxLength={500} />
          </Form.Item>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="originalPrice"
                label="原价(元)"
                rules={[{ required: true, message: '请输入原价' }]}
              >
                <InputNumber
                  min={0.01}
                  precision={2}
                  style={{ width: '100%' }}
                  placeholder="请输入原价"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="groupPrice"
                label="团购价(元)"
                rules={[{ required: true, message: '请输入团购价' }]}
              >
                <InputNumber
                  min={0.01}
                  precision={2}
                  style={{ width: '100%' }}
                  placeholder="请输入团购价"
                />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="minCount"
                label="最小开团人数"
                rules={[{ required: true, message: '请输入最小开团人数' }]}
              >
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="maxCount"
                label="最大开团人数"
                rules={[{ required: true, message: '请输入最大开团人数' }]}
              >
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="timeRange"
            label="活动时间"
            rules={[{ required: true, message: '请选择活动时间' }]}
          >
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="activityRules"
            label="活动规则"
          >
            <TextArea placeholder="请输入活动规则" rows={4} />
          </Form.Item>

          <Form.Item
            name="serviceTerms"
            label="服务条款"
          >
            <TextArea placeholder="请输入服务条款" rows={4} />
          </Form.Item>

          <Form.Item
            label="团购图片"
          >
            <Upload
              listType="picture-card"
              fileList={fileList}
              onChange={handleUploadChange}
              customRequest={customUpload}
              multiple
            >
              {fileList.length >= 8 ? null : (
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>上传</div>
                </div>
              )}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default MeituanGroupPage; 